﻿Imports System.Net
Imports System.IO
Partial Class DownloadFile
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim sharePointListPath As String = ConfigurationManager.AppSettings("SharePointServer")
        Dim filename As String = Request("filename")
        Dim qrst As String = Request("filepath")
        Try

            


            Dim webRequest As HttpWebRequest = webRequest.Create(sharePointListPath & qrst)
            webRequest.Credentials = CredentialCache.DefaultCredentials
            webRequest.Method = "GET"
            webRequest.ContentType = "application/x-www-form-urlencoded"
            webRequest.CookieContainer = New CookieContainer()

            Dim bytesProcessed As Integer = 0
            Dim remoteStream As Stream
            Dim localStream As Stream
            Dim resp As WebResponse = Nothing
            Dim memStream As New MemoryStream(1023)

            resp = webRequest.GetResponse()
            If Not resp Is Nothing Then
                remoteStream = resp.GetResponseStream()
                'localStream = File.Create(targetfile)

                'Declare buffer as byte array
                Dim myBuffer As Byte()
                'Byte array initialization 
                ReDim myBuffer(1023)


                Dim bytesRead As Integer
                bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                Do While (bytesRead > 0)
                    'localStream.Write(myBuffer, 0, bytesRead)
                    memStream.Write(myBuffer, 0, bytesRead)
                    bytesProcessed += bytesRead
                    bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                Loop
                'localStream.Close()
                Dim bytest As Byte() = memStream.ToArray()
                memStream.Close()

                Response.Clear()
                Response.ClearHeaders()
                Response.ClearContent()
                'Response.AddHeader("Content-Disposition", "attachment; filename=" + filename)
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8))
                Response.AddHeader("Content-Length", bytesProcessed.ToString())
                Response.ContentType = "text/plain"
                If Response.Headers("GENERATOR") = "Microsoft Sharepoint" Then
                    Response.Write("หากไม่สามารถดาวน์โหลดได้กรุณา <a href='" & sharePointListPath & qrst & "'>คลิกที่นี่</a>")
                    Exit Sub
                End If
                Response.Flush()
                Response.BinaryWrite(bytest)
                Response.End()
            End If

        Catch ex As Exception
            Response.Write("หากไม่สามารถดาวน์โหลดได้กรุณา <a href='" & sharePointListPath & qrst & "'>คลิกที่นี่</a>")
        End Try
    End Sub
End Class
